package com.bsj.pay.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.bsj.pay.config.GlobalConfig;
import com.bsj.pay.model.MerchantBean;
import com.bsj.pay.model.PartnerBean;
import com.bsj.pay.model.UserBean;
import com.bsj.pay.service.ConfigService;
import com.bsj.pay.util.HttpUtil;

@Component
public class AuthInterceptor implements HandlerInterceptor {
	
	private Log log = LogFactory.getLog(AuthInterceptor.class);
	
	@Autowired
	private ConfigService configService;
	
    public AuthInterceptor() {  
        // TODO Auto-generated constructor stub  
    }  
  
    /** 
     * 在业务处理器处理请求之前被调用 
     * 如果返回false 
     *     从当前的拦截器往回执行所有拦截器的afterCompletion(),再退出拦截器链 
     *  
     * 如果返回true 
     *    执行下一个拦截器,直到所有的拦截器都执行完毕 
     *    再执行被拦截的Controller 
     *    然后进入拦截器链, 
     *    从最后一个拦截器往回执行所有的postHandle() 
     *    接着再从最后一个拦截器往回执行所有的afterCompletion() 
     */  
    @Override  
    public boolean preHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler) throws Exception {
    	if(!GlobalConfig.isInit)configService.init();
    	String ip=HttpUtil.getIpAddr(request);
    	/*log.info("request ip:"+ip);
    	String requestURL = request.getRequestURL().toString();
    	log.info("request url:"+requestURL);
    	Map<String,String> requestParam=HttpUtil.getParameterMap(request);
    	log.info("request param:"+JSONUtil.toJson(requestParam));*/
    	String path = request.getServletPath();
    	if (path.startsWith("/api") || path.contains("/login.html")|| path.contains("/loginPage.html")) {
			return true;
		}
    	if(path.startsWith("/admin"))
    	{
    		UserBean user=(UserBean) request.getSession().getAttribute("auser");
    		if(user==null)
            {
            	response.sendRedirect(request.getContextPath()+"/admin/loginPage.html");
            	return false;
            }
        	if(!StringUtils.isEmpty(user.getBind_ip())&&!user.getBind_ip().contains(ip))
        	{
        		return false;
        	}
    	}
    	if(path.startsWith("/merchant"))
    	{
     		MerchantBean user=(MerchantBean) request.getSession().getAttribute("muser");
    		if(user==null)
            {
            	response.sendRedirect(request.getContextPath()+"/merchant/loginPage.html");
            	return false;
            }
    	}
     	if(path.startsWith("/partner"))
    	{
     		PartnerBean user=(PartnerBean) request.getSession().getAttribute("puser");
    		if(user==null)
            {
            	response.sendRedirect(request.getContextPath()+"/partner/loginPage.html");
            	return false;
            }
    	}
        return true; 
    }  
  
    //在业务处理器处理请求执行完成后,生成视图之前执行的动作   
    @Override  
    public void postHandle(HttpServletRequest request,  
            HttpServletResponse response, Object handler,  
            ModelAndView modelAndView) throws Exception {  
        // TODO Auto-generated method stub  
//        System.out.println("==============执行顺序: 2、postHandle================"); 
    }  
    
  
    /** 
     * 在DispatcherServlet完全处理完请求后被调用  
     *  
     *   当有拦截器抛出异常时,会从当前拦截器往回执行所有的拦截器的afterCompletion() 
     */  
    @Override  
    public void afterCompletion(HttpServletRequest request,  
            HttpServletResponse response, Object handler, Exception ex)  
            throws Exception {  
        // TODO Auto-generated method stub  
//        System.out.println("==============执行顺序: 3、afterCompletion================");  
    }  
}
